package org.springblade.modules.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.constant.BaseRoleConstant;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.plan.PlanContentExcelSearchDTO;
import org.springblade.modules.admin.dto.sugar.SugarSearchDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.MaintainPlanContentStatusEnum;
import org.springblade.modules.admin.enums.SignStatusEnum;
import org.springblade.modules.admin.mapper.PlanContentExcelMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.plan.PerformanceVoV2;
import org.springblade.modules.admin.vo.sugar.*;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zcc
 * @version 1.0
 * @date 2021/11/15 9:45
 */
@Service
public class SugarServiceImpl extends BaseServiceImpl<PlanContentExcelMapper, MaintainPlanContent> implements SugarService {

	@Resource
	private IMaintainSignService maintainSignService;

	@Resource
	private UserMapper userMapper;

	@Resource
	private IRoleService roleService;

	@Resource
	private IBuildingContractPlusService buildingContractPlusService;

	@Resource
	private ElevatorService elevatorService;
	@Autowired
	private IMaintainDayCountService maintainDayCountService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	private ElevatorPrincipalDeptService elevatorPrincipalDeptService;

	//
//	private List<TimelinessVO> getTimelinessRatio(SugarSearchVO sugarSearchVO) {
//
//
//		List<TimelinessVO> list = new ArrayList<>(50);
//
//		List<MaintainPlanContent> maintainPlanContents = baseMapper.list(sugarSearchVO);
//		maintainPlanContents.forEach(o -> {
//			String date = o.getPlanDate() + " 00:00:00";
//			String format = DateUtil.format(DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss"), "yyyy-MM");
//			o.setShortPlanDate(format);
//		});
//		List<String> planDatesList = maintainPlanContents.stream().map(MaintainPlanContent::getShortPlanDate).collect(Collectors.toList());
//		List<String> planDates = planDatesList.stream().distinct().collect(Collectors.toList());
//		List<Long> ids = maintainPlanContents.stream().filter(o -> o.getStatus() == 4).distinct().map(MaintainPlanContent::getId).collect(Collectors.toList());
//
//		Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().in(MaintainSign::getElevatorPlanId, ids)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//
//		Map<String, List<MaintainPlanContent>> listMap = maintainPlanContents.stream().collect(Collectors.groupingBy(MaintainPlanContent::getShortPlanDate));
//		for (String planDate : planDates) {
//			TimelinessVO timelinessVO = new TimelinessVO();
//			Integer timelinessCounts = timelinessVO.getTimelinessCounts();
//			List<MaintainPlanContent> planContents = listMap.get(planDate);
//			List<MaintainPlanContent> finishList = planContents.stream().filter(o -> o.getStatus() == 4).collect(Collectors.toList());
//			for (MaintainPlanContent maintainPlanContent : finishList) {
//				DateTime createTime = DateUtil.parse(maintainPlanContent.getPlanDate() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
//				List<MaintainSign> maintainSigns = signMap.get(maintainPlanContent.getId());
//				if (maintainSigns != null && maintainSigns.size() > 0) {
//					Optional<MaintainSign> first = maintainSigns.stream().filter(o -> o.getStatus() == 2).findFirst();
//					if (first.isPresent()) {
//						MaintainSign maintainSign = first.get();
//						Integer days = Convert.toInt(DateUtil.betweenDay(createTime, maintainSign.getCreateTime(), false));
//						timelinessCounts = timelinessCounts + (days < 2 ? 1 : 0);
//
//					}
//				}
//			}
//			timelinessVO.setMonth(planDate);
//			timelinessVO.setShortMonth(planDate.substring(planDate.indexOf("-") + 1, planDate.length()) + "月");
//			timelinessVO.setTimelinessCounts(timelinessCounts);
//			timelinessVO.setCounts(planContents.size());
//			timelinessVO.setTimelinessRatio(Convert.toBigDecimal(timelinessCounts).divide(Convert.toBigDecimal(planContents.size()), 2, RoundingMode.HALF_UP));
//			timelinessVO.setFinishRatio(Convert.toBigDecimal(finishList.size()).divide(Convert.toBigDecimal(planContents.size()), 2, RoundingMode.HALF_UP));
//			list.add(timelinessVO);
//		}
//
//		return list;
//
//	}
//
//	@Override
//	public TimelinessResultVO getFinishRatio(SugarSearchVO sugarSearchVO) {
//
//		List<TimelinessVO> list = getTimelinessRatio(sugarSearchVO);
//		TimelinessResultVO timelinessResultVO = new TimelinessResultVO();
//		List<String> categoriesList = new ArrayList<>(16);
//		List<String> seriesDataList = new ArrayList<>(16);
//		for (TimelinessVO timelinessVO : list) {
//			categoriesList.add(timelinessVO.getShortMonth());
//			seriesDataList.add(Convert.toStr(timelinessVO.getFinishRatio()));
//		}
//		timelinessResultVO.setCategories(categoriesList.toArray(new String[]{}));
//
//		TimelinesSseriesDataVO timelinesSseriesDataVO = new TimelinesSseriesDataVO();
//		timelinesSseriesDataVO.setName("完成率");
//		timelinesSseriesDataVO.setData(seriesDataList.toArray(new String[]{}));
//		TimelinesSseriesDataVO[] result = {timelinesSseriesDataVO};
//		timelinessResultVO.setSeries(result);
//
//		return timelinessResultVO;
//	}
//
//	@Override
//	public RankingListVO getRankingList(SugarSearchVO sugarSearchVO) {
//
//		RankingListVO rankingListVO = new RankingListVO();
//		List<MaintainPlanContent> sugarRankingList = baseMapper.getSugarRankingList(sugarSearchVO);
//		List<Long> ids = sugarRankingList.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
//		List<String> buildingNames = sugarRankingList.stream().map(MaintainPlanContent::getBuildingName).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
//		Map<String, List<MaintainPlanContent>> listMap = sugarRankingList.stream().collect(Collectors.groupingBy(MaintainPlanContent::getBuildingName));
//		Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().in(MaintainSign::getElevatorPlanId, ids)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//		List<RowPlus> rows = new ArrayList<>(20);
//		for (String buildingName : buildingNames) {
//			List<MaintainPlanContent> maintainPlanContents = listMap.get(buildingName);
//			RowPlus row = new RowPlus();
//			row.set小区名称(buildingName);
//			List<MaintainPlanContent> finishList = maintainPlanContents.stream().filter(o -> o.getStatus() == 4).collect(Collectors.toList());
//			Integer timelinessCounts = 0;
//			for (MaintainPlanContent maintainPlanContent : finishList) {
//				DateTime createTime = DateUtil.parse(maintainPlanContent.getPlanDate() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
//				List<MaintainSign> maintainSigns = signMap.get(maintainPlanContent.getId());
//				if (maintainSigns != null && maintainSigns.size() > 0) {
//					Optional<MaintainSign> first = maintainSigns.stream().filter(o -> o.getStatus() == 2).findFirst();
//					if (first.isPresent()) {
//						MaintainSign maintainSign = first.get();
//						if (maintainSign.getCreateTime().getTime() > createTime.getTime()) {
//							Integer days = Convert.toInt(DateUtil.betweenDay(createTime, maintainSign.getCreateTime(), false));
//							timelinessCounts = timelinessCounts + (days < 2 ? 1 : 0);
//						} else {
//							timelinessCounts = timelinessCounts + 1;
//						}
//
//					}
//				}
//			}
//			row.setTimelinessCounts(timelinessCounts);
//			if (timelinessCounts > 0) {
//				row.set及时率(Convert.toBigDecimal(timelinessCounts).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, RoundingMode.HALF_UP));
//				rows.add(row);
//			}
//
//
//		}
//		Collections.sort(rows, new Comparator<RowPlus>() {
//			@Override
//			public int compare(RowPlus o1, RowPlus o2) {
//				return o2.getTimelinessCounts() - o1.getTimelinessCounts();
//			}
//		});
//		List<Row> rows2 = new ArrayList<>(20);
//		for (int i = 0; i < rows.size(); i++) {
//			Row row = new Row();
//			BeanUtil.copyProperties(rows.get(i), row);
//			row.set排名("No." + (i + 1));
//			rows2.add(row);
//		}
//		rankingListVO.setRows(rows2.toArray(new Row[]{}));
//		Column column1 = new Column("排名", "排名");
//		Column column2 = new Column("小区名称", "小区名称");
//		Column column3 = new Column("及时率", "及时率");
//		Column[] columns = {column1, column2, column3};
//		rankingListVO.setColumns(columns);
//		return rankingListVO;
//	}
//
//	@Override
//	public BigDecimal getTimelinessAndFinishRatio(Integer type) {
//
//		List<MaintainPlanContent> maintainPlanContents = maintainPlanContentService.list(Wrappers.<MaintainPlanContent>lambdaQuery().eq(MaintainPlanContent::getTypeStatus, MaintainPlanContentEnum.MAINTAIN_BY.getId()));
//		List<MaintainPlanContent> planContents = maintainPlanContents.stream().filter(o -> o.getStatus() == MaintainPlanContentStatusEnum.FINISH.getId()).collect(Collectors.toList());
//		if (type == 1) {
//			return Convert.toBigDecimal(planContents.size()).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, RoundingMode.HALF_UP);
//		} else if (type == 2) {
//			List<Long> ids = planContents.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
//			Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().in(MaintainSign::getElevatorPlanId, ids)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//			Integer timelinessCounts = 0;
//			for (MaintainPlanContent maintainPlanContent : planContents) {
//				try {
//					DateTime createTime = DateUtil.parse(maintainPlanContent.getPlanDate() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
//					List<MaintainSign> maintainSigns = signMap.get(maintainPlanContent.getId());
//					if (maintainSigns != null && maintainSigns.size() > 0) {
//						Optional<MaintainSign> first = maintainSigns.stream().filter(o -> o.getStatus() == 2).findFirst();
//						if (first.isPresent()) {
//							MaintainSign maintainSign = first.get();
//							Integer days = Convert.toInt(DateUtil.betweenDay(createTime, maintainSign.getCreateTime(), false));
//							timelinessCounts = timelinessCounts + (days < 2 ? 1 : 0);
//						}
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//					System.out.println(maintainPlanContent.getId());
//				}
//			}
//			return Convert.toBigDecimal(timelinessCounts).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, RoundingMode.HALF_UP);
//
//		}
//		return new BigDecimal(0);
//	}
//
//	@Override
//	public BuildingInfoVo getBuildingInfo(SugarSearchDTO sugarSearchDTO) {
//		//1:小区，2：别墅，7：工厂
//		List<Integer> buildingTypes = Arrays.asList(0, 1, 2, 7);
//		BuildingInfoVo buildingInfoVo = baseMapper.getBuildingInfo(sugarSearchDTO);
//		List<BuildingTypeInfoVo> buildingTypeInfoVos = baseMapper.getBuildingTypeInfo(sugarSearchDTO);
//
//		List<ElevatorInfoVo> elevatorInfoVos = baseMapper.getElevatorInfo(sugarSearchDTO);
//		List<ElevatorInfoBrandVo> elevatorInfoBrandVos = baseMapper.getElevatorInfoBrand(sugarSearchDTO);
//		List<BuildingTypeInfoVo> buildingTypeInfoVos2 = new ArrayList<>(5);
//		Integer typeCounts = 0;
//		for (int i = 0; i < buildingTypeInfoVos.size(); i++) {
//			if(buildingTypes.contains(buildingTypeInfoVos.get(i).getId())){
//				buildingTypeInfoVos2.add(buildingTypeInfoVos.get(i));
//			}else{
//				typeCounts = typeCounts + buildingTypeInfoVos.get(i).getCounts();
//			}
//		}
//		BuildingTypeInfoVo buildingTypeInfoVo = new BuildingTypeInfoVo();
//		buildingTypeInfoVo.setCounts(typeCounts);
//		buildingTypeInfoVo.setName("其它");
//		buildingTypeInfoVos2.add(buildingTypeInfoVo);
//		buildingInfoVo.setElevatorInfoVos(elevatorInfoVos);
//		buildingInfoVo.setBuildingTypeInfoVos(buildingTypeInfoVos2);
//		buildingInfoVo.setElevatorInfoBrandVos(elevatorInfoBrandVos);
//		return buildingInfoVo;
//	}
//
//	@Override
//	public WorkPlanInfoVo getWorkPlanInfo(SugarSearchDTO sugarSearchDTO) {
//
//		WorkPlanInfoVo workPlanInfoVo = baseMapper.getWorkPlanInfo(sugarSearchDTO);
//
//		//获取组员信息
//		List<PerformanceVoV2> groupUserList = baseMapper.getGroupUserList();
//		List<Long> userIds = groupUserList.stream().map(PerformanceVoV2::getUserId).collect(Collectors.toList());
//		Map<String, List<PerformanceVoV2>> listMap = groupUserList.stream().collect(Collectors.groupingBy(PerformanceVoV2::getGroupId));
//		List<String> groupIds = groupUserList.stream().map(PerformanceVoV2::getGroupId).distinct().collect(Collectors.toList());
//
//		//设置查询条件
//		PlanContentExcelSearchDTO planContentExcelSearchDTO = new PlanContentExcelSearchDTO();
//		planContentExcelSearchDTO.setStartDate(DateUtil.beginOfMonth(new Date()));
//		planContentExcelSearchDTO.setEndDate(DateUtil.endOfMonth(new Date()));
//		planContentExcelSearchDTO.setStartTime(DateUtil.format(DateUtil.beginOfMonth(new Date()), "yyyy-MM-dd"));
//		planContentExcelSearchDTO.setEndTime(DateUtil.format(DateUtil.endOfMonth(new Date()), "yyyy-MM-dd"));
//		planContentExcelSearchDTO.setUserIds(userIds);
//		List<MaintainPlanContent> maintainPlanContents = baseMapper.planListByUserId(planContentExcelSearchDTO);
//
//
//		//进行分组处理
//		Map<Long, List<MaintainPlanContent>> longListMap = maintainPlanContents.stream().collect(Collectors.groupingBy(MaintainPlanContent::getMaintainUserId));
//		List<WorkPlanOfGroupDetailVo> list = new ArrayList<>(20);
//		for (String groupId : groupIds) {
//			List<PerformanceVoV2> performanceVoV2s = listMap.get(groupId);
//			if (performanceVoV2s != null && performanceVoV2s.size() > 0) {
//				Integer elevatorCounts = 0;
//				Integer planCounts = 0;
//				for (PerformanceVoV2 performanceVoV2 : performanceVoV2s) {
//					List<MaintainPlanContent> contentList = longListMap.get(performanceVoV2.getUserId());
//					if (contentList != null && contentList.size() > 0) {
//						List<Long> elevatorIds = contentList.stream().map(MaintainPlanContent::getElevatorId).distinct().collect(Collectors.toList());
//						elevatorCounts = elevatorCounts + elevatorIds.size();
//						planCounts = planCounts + contentList.size();
//					}
//				}
//				if (planCounts > 0) {
//					WorkPlanOfGroupDetailVo workPlanOfGroupDetailVo = new WorkPlanOfGroupDetailVo();
//					workPlanOfGroupDetailVo.setGroupName(performanceVoV2s.get(0).getGroupName());
//					BigDecimal divide1 = Convert.toBigDecimal(elevatorCounts).divide(Convert.toBigDecimal(performanceVoV2s.size()), 2, BigDecimal.ROUND_HALF_UP);
//					BigDecimal divide2 = Convert.toBigDecimal(planCounts).divide(Convert.toBigDecimal(performanceVoV2s.size()), 2, BigDecimal.ROUND_HALF_UP);
//					BigDecimal divide3 = Convert.toBigDecimal(planCounts).multiply(Convert.toBigDecimal("0.75")).divide(Convert.toBigDecimal(performanceVoV2s.size()), 2, BigDecimal.ROUND_HALF_UP);
//					workPlanOfGroupDetailVo.setAvgElevatorCounts(divide1);
//					workPlanOfGroupDetailVo.setAvgWorkCounts(divide2);
//					workPlanOfGroupDetailVo.setAvgTimeOfHours(divide3);
//					list.add(workPlanOfGroupDetailVo);
//				}
//
//			}
//
//		}
//		workPlanInfoVo.setList(list);
//		return workPlanInfoVo;
//	}
//
	@Override
	public ElevatorAndUserInfoVo getEleVatorAndUserInfo(SugarSearchDTO sugarSearchDTO) {
		ElevatorAndUserInfoVo elevatorAndUserInfoVo = new ElevatorAndUserInfoVo();
		List<Long> deptIds = deptService.selectDeptAndAllChildIds(sugarSearchDTO.getDeptIds());
		Long groupRoleId1 = roleService.getRoleIdByAliases(AuthUtil.getTenantId(), BaseRoleConstant.REPAIR);
		if (groupRoleId1 == null) {
			elevatorAndUserInfoVo.setMalUserCounts(0);
		} else {
			final List<User> userCounts1 = userMapper.selectList(Wrappers.<User>lambdaQuery().like(User::getRoleId,groupRoleId1).eq(User::getStatus,1));
			final List<Long> list1 = new ArrayList<>();
			if(Func.isNotEmpty(userCounts1)){
				deptIds.forEach(e -> {
					list1.addAll(userCounts1.stream().filter(u -> u.getDeptId().contains(String.valueOf(e))).map(User::getId).collect(Collectors.toList()));
				});
			}
			elevatorAndUserInfoVo.setMalUserCounts(list1.stream().distinct().collect(Collectors.toList()).size());
		}

		Long groupRoleId2 = roleService.getRoleIdByAliases(AuthUtil.getTenantId(), BaseRoleConstant.MAINTENANCE);
		if (groupRoleId2 == null) {
			elevatorAndUserInfoVo.setUserCounts(0);
		} else {
			final List<User> userCounts2 = userMapper.selectList(Wrappers.<User>lambdaQuery().like(User::getRoleId,groupRoleId2).eq(User::getStatus,1));
			final List<Long> list2 = new ArrayList<>();
			if(Func.isNotEmpty(userCounts2)){
				deptIds.forEach(e -> {
					list2.addAll(userCounts2.stream().filter(u -> u.getDeptId().contains(String.valueOf(e))).map(User::getId).collect(Collectors.toList()));
				});
			}
			elevatorAndUserInfoVo.setUserCounts(list2.stream().distinct().collect(Collectors.toList()).size());
		}

		List<ElevatorPrincipalDept> elevatorDepts = elevatorPrincipalDeptService.list(Wrappers.<ElevatorPrincipalDept>lambdaQuery().in(ElevatorPrincipalDept::getDeptId,deptIds));
		List<Long> elevatorIds = elevatorDepts.stream().map(ElevatorPrincipalDept::getElevatorId).collect(Collectors.toList());
		sugarSearchDTO.setElevatorIds(elevatorIds);
		if(Func.isNotEmpty(elevatorIds)){
			elevatorAndUserInfoVo.setElevatorCounts(buildingContractPlusService.getValidElevator(sugarSearchDTO));
		}else {
			elevatorAndUserInfoVo.setElevatorCounts(0);
		}
		elevatorAndUserInfoVo.setRatioDesc("1:0");
		if(elevatorAndUserInfoVo.getUserCounts() > 0){
			final BigDecimal divide = Convert.toBigDecimal(elevatorAndUserInfoVo.getElevatorCounts()).divide(Convert.toBigDecimal(elevatorAndUserInfoVo.getUserCounts()), 1, BigDecimal.ROUND_HALF_UP);
			elevatorAndUserInfoVo.setRatioDesc("1:" + divide.toString());
		}

		return elevatorAndUserInfoVo;
	}

	//
//	@Override
//	public CarryOutVo getCarryOutInfo(SugarSearchDTO sugarSearchDTO) {
//		CarryOutVo carryOutVo = new CarryOutVo();
//		List<MaintainPlanContent> maintainPlanContents = baseMapper.getMaintainPlanContentList(sugarSearchDTO);
//		if (maintainPlanContents.size() == 0) {
//			return carryOutVo;
//		}
//		List<MaintainPlanContent> finishList = maintainPlanContents.stream().filter(o -> o.getStatus() == MaintainPlanContentStatusEnum.FINISH.getId()).collect(Collectors.toList());
//		carryOutVo.setFinishRatio(Convert.toBigDecimal(finishList.size()).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, BigDecimal.ROUND_HALF_UP));
//		if (finishList.size() > 0) {
//			List<Long> finishIds = finishList.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
//			Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getStatus, 1).in(MaintainSign::getElevatorPlanId, finishIds)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//			long minutes = 0L;
//			List<MaintainPlanContent> workloadList = new ArrayList<>();
//			List<MaintainPlanContent> workloadList2 = new ArrayList<>();
//			for (int i = 0; i < finishList.size(); i++) {
//
//				MaintainPlanContent o = finishList.get(i);
//				Date parse = DateUtil.parse(o.getPlanDate() + " 00:00:00");
//				Date updateTime = DateUtil.parse(DateUtil.format(o.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
//
//				List<MaintainSign> maintainSigns = signMap.get(o.getId());
//				Date signDate = null;
//				if (maintainSigns != null) {
//					if (maintainSigns.size() > 1) {
//						List<Date> dateList = new ArrayList<>(5);
//						for (int j = 0; j < maintainSigns.size(); j++) {
//							dateList.add(maintainSigns.get(j).getCreateTime());
//						}
//						signDate = Collections.min(dateList);
//					} else if (maintainSigns.size() == 1) {
//						signDate = maintainSigns.get(0).getCreateTime();
//					}
//					if (signDate != null) {
//						minutes = minutes + DateUtil.between(signDate, updateTime, DateUnit.MINUTE);
//					}
//				}
//				if (updateTime.getTime() > parse.getTime()) {
//					if (DateUtil.betweenDay(parse, updateTime, true) >= 2) {
//						workloadList.add(o);
//					} else {
//						workloadList2.add(o);
//					}
//				} else {
//					workloadList2.add(o);
//				}
//			}
//			carryOutVo.setTimelinessRatio(Convert.toBigDecimal(workloadList2.size()).divide(Convert.toBigDecimal(finishList.size()), 2, BigDecimal.ROUND_HALF_UP));
//			carryOutVo.setTimelinessCounts(workloadList2.size());
//			carryOutVo.setDeferredElevatorCounts(workloadList.size());
//			carryOutVo.setAvgWorkMinute(Convert.toInt(Convert.toBigDecimal(minutes).divide(Convert.toBigDecimal(finishList.size()), 0, BigDecimal.ROUND_HALF_UP)));
//			carryOutVo.setFinishWorkload(finishList.size());
//		}
//		carryOutVo.setPlanWorkload(maintainPlanContents.size());
//		carryOutVo.setMonth(Convert.toInt(DateUtil.format(new Date(), "yyyyMM")));
//
//		BigDecimal divide = carryOutVo.getFinishRatio().add(carryOutVo.getTimelinessRatio()).add(carryOutVo.getEffectiveRatio()).divide(Convert.toBigDecimal(3), 1, BigDecimal.ROUND_HALF_UP);
//		carryOutVo.setCommentRatio(divide);
//
//		Integer endMonth = Convert.toInt(DateUtil.format(DateUtil.lastMonth(), "yyyyMM"));
//		Integer beginMonth = Convert.toInt(DateUtil.format(DateUtil.offsetMonth(DateUtil.lastMonth(), -3), "yyyyMM"));
//		List<PlanContentStatistical> statisticals = planContentStatisticalService.list(Wrappers.<PlanContentStatistical>lambdaQuery().between(PlanContentStatistical::getMonth, beginMonth, endMonth));
//		List<CarryOutVo> resultList = new ArrayList<>(8);
//		for (int i = 0; i < statisticals.size(); i++) {
//			CarryOutVo cov = new CarryOutVo();
//			BeanUtil.copyProperties(statisticals.get(i), cov);
//			resultList.add(cov);
//		}
//		carryOutVo.setMonthList(resultList);
//
//		return carryOutVo;
//	}
//
//	@Override
//	public List<CarryOutVo> getCarryOutVoOrderByGroupId(Integer type) {
//		List<CarryOutVo> resultList = new ArrayList<>(50);
//		if (type == 1) {
//			List<Building> list = buildingService.list();
//			List<Long> ids = list.stream().map(Building::getId).collect(Collectors.toList());
//			PlanContentExcelSearchDTO planContentExcelSearchDTO = new PlanContentExcelSearchDTO();
//			planContentExcelSearchDTO.setEndDate(new Date());
//			planContentExcelSearchDTO.setStartDate(DateUtil.beginOfMonth(new Date()));
//			planContentExcelSearchDTO.setBuildingIds(ids);
//			planContentExcelSearchDTO.setEndTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
//			planContentExcelSearchDTO.setStartTime(DateUtil.format(DateUtil.beginOfMonth(new Date()), "yyyy-MM-dd"));
//			List<MaintainPlanContent> maintainPlanContentList = baseMapper.getPlanListByBuildingIds(planContentExcelSearchDTO);
//			Map<String, List<MaintainPlanContent>> listMap = maintainPlanContentList.stream().collect(Collectors.groupingBy(MaintainPlanContent::getBuildingName));
//			for (Building building : list) {
//				List<MaintainPlanContent> maintainPlanContents = listMap.get(Convert.toStr(building.getId()));
//				CarryOutVo carryOutVo = new CarryOutVo();
//				carryOutVo.setBuildingName(building.getName());
//				if (maintainPlanContents != null && maintainPlanContents.size() > 0) {
//					List<MaintainPlanContent> finishList = maintainPlanContents.stream().filter(o -> o.getStatus() == MaintainPlanContentStatusEnum.FINISH.getId()).collect(Collectors.toList());
//					carryOutVo.setFinishRatio(Convert.toBigDecimal(finishList.size()).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, BigDecimal.ROUND_HALF_UP));
//					if (finishList.size() > 0) {
//
//						List<Long> finishIds = finishList.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
//						Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getStatus, 1).in(MaintainSign::getElevatorPlanId, finishIds)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//
//						long minutes = 0L;
//						List<MaintainPlanContent> workloadList = new ArrayList<>();
//						List<MaintainPlanContent> workloadList2 = new ArrayList<>();
//						for (int i = 0; i < finishList.size(); i++) {
//							MaintainPlanContent o = finishList.get(i);
//							Date parse = DateUtil.parse(o.getPlanDate() + " 00:00:00");
//							Date updateTime = DateUtil.parse(DateUtil.format(o.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
//
//							List<MaintainSign> maintainSigns = signMap.get(o.getId());
//							Date signDate = null;
//							if (maintainSigns.size() > 1) {
//								List<Date> dateList = new ArrayList<>(5);
//								for (int j = 0; j < maintainSigns.size(); j++) {
//									dateList.add(maintainSigns.get(j).getCreateTime());
//								}
//								signDate = Collections.min(dateList);
//							} else if (maintainSigns.size() == 1) {
//								signDate = maintainSigns.get(0).getCreateTime();
//							}
//							if (signDate != null) {
//								minutes = minutes + DateUtil.between(signDate, updateTime, DateUnit.MINUTE);
//							}
//
//							if (updateTime.getTime() > parse.getTime()) {
//								if (DateUtil.betweenDay(parse, updateTime, true) >= 2) {
//									workloadList.add(o);
//								} else {
//									workloadList2.add(o);
//								}
//							} else {
//								workloadList2.add(o);
//							}
//						}
//						carryOutVo.setTimelinessRatio(Convert.toBigDecimal(workloadList2.size()).divide(Convert.toBigDecimal(finishList.size()), 2, BigDecimal.ROUND_HALF_UP));
//						carryOutVo.setTimelinessCounts(workloadList2.size());
//						carryOutVo.setDeferredElevatorCounts(workloadList.size());
//						carryOutVo.setAvgWorkMinute(Convert.toInt(Convert.toBigDecimal(minutes).divide(Convert.toBigDecimal(finishList.size()), 0, BigDecimal.ROUND_HALF_UP)));
//					}
//					carryOutVo.setPlanWorkload(maintainPlanContents.size());
//					carryOutVo.setFinishWorkload(finishList.size());
//					resultList.add(carryOutVo);
//				}
//			}
//		} else {
//			List<PerformanceVoV2> list = baseMapper.getGroupUserList();
//			Map<String, List<PerformanceVoV2>> listMap1 = list.stream().collect(Collectors.groupingBy(PerformanceVoV2::getGroupId));
//			List<String> groupIds = list.stream().map(PerformanceVoV2::getGroupId).distinct().collect(Collectors.toList());
//			PlanContentExcelSearchDTO planContentExcelSearchDTO = new PlanContentExcelSearchDTO();
//			planContentExcelSearchDTO.setEndDate(new Date());
//			planContentExcelSearchDTO.setStartDate(DateUtil.beginOfMonth(new Date()));
//			planContentExcelSearchDTO.setGroupIds(groupIds);
//			List<MaintainPlanContent> planListByGroupId = baseMapper.getPlanListByGroupId(planContentExcelSearchDTO);
//			Map<Long, List<MaintainPlanContent>> listMap = planListByGroupId.stream().collect(Collectors.groupingBy(MaintainPlanContent::getGroupId));
//			for (String groupId : groupIds) {
//				CarryOutVo carryOutVo = new CarryOutVo();
//				PerformanceVoV2 performanceVoV2 = listMap1.get(groupId).get(0);
//				String groupName = performanceVoV2.getGroupName();
//				carryOutVo.setGroupName(performanceVoV2.getGroupName());
//				List<MaintainPlanContent> maintainPlanContents = listMap.get(Convert.toLong(groupId));
//				if (maintainPlanContents != null && maintainPlanContents.size() > 0) {
//					List<MaintainPlanContent> finishList = maintainPlanContents.stream().filter(o -> o.getStatus() == MaintainPlanContentStatusEnum.FINISH.getId()).collect(Collectors.toList());
//					carryOutVo.setFinishRatio(Convert.toBigDecimal(finishList.size()).divide(Convert.toBigDecimal(maintainPlanContents.size()), 2, BigDecimal.ROUND_HALF_UP));
//					if (finishList.size() > 0) {
//						List<Long> finishIds = finishList.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
//						Map<Long, List<MaintainSign>> signMap = maintainSignService.list(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getStatus, 1).in(MaintainSign::getElevatorPlanId, finishIds)).stream().collect(Collectors.groupingBy(MaintainSign::getElevatorPlanId));
//
//						long minutes = 0L;
//
//						List<MaintainPlanContent> workloadList = new ArrayList<>();
//						List<MaintainPlanContent> workloadList2 = new ArrayList<>();
//						for (int i = 0; i < finishList.size(); i++) {
//							MaintainPlanContent o = finishList.get(i);
//							Date parse = DateUtil.parse(o.getPlanDate() + " 00:00:00");
//							Date updateTime = DateUtil.parse(DateUtil.format(o.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
//							List<MaintainSign> maintainSigns = signMap.get(o.getId());
//							Date signDate = null;
//							if (maintainSigns.size() > 1) {
//								List<Date> dateList = new ArrayList<>(5);
//								for (int j = 0; j < maintainSigns.size(); j++) {
//									dateList.add(maintainSigns.get(j).getCreateTime());
//								}
//								signDate = Collections.min(dateList);
//							} else if (maintainSigns.size() == 1) {
//								signDate = maintainSigns.get(0).getCreateTime();
//							}
//							if (signDate != null) {
//								minutes = minutes + DateUtil.between(signDate, updateTime, DateUnit.MINUTE);
//							}
//
//							if (updateTime.getTime() > parse.getTime()) {
//								if (DateUtil.betweenDay(parse, updateTime, true) >= 2) {
//									workloadList.add(o);
//								} else {
//									workloadList2.add(o);
//								}
//							} else {
//								workloadList2.add(o);
//							}
//						}
//						carryOutVo.setTimelinessRatio(Convert.toBigDecimal(workloadList2.size()).divide(Convert.toBigDecimal(finishList.size()), 2, BigDecimal.ROUND_HALF_UP));
//						carryOutVo.setTimelinessCounts(workloadList2.size());
//						carryOutVo.setDeferredElevatorCounts(workloadList.size());
//						carryOutVo.setAvgWorkMinute(Convert.toInt(Convert.toBigDecimal(minutes).divide(Convert.toBigDecimal(finishList.size()), 0, BigDecimal.ROUND_HALF_UP)));
//					}
//					carryOutVo.setPlanWorkload(maintainPlanContents.size());
//					carryOutVo.setFinishWorkload(finishList.size());
//					resultList.add(carryOutVo);
//				}
//
//			}
//		}
//		return resultList;
//	}
//
//	@Override
//	public SignDetailVo getSignDetail(SugarSearchDTO sugarSearchDTO) {
//
//		SignDetailVo signDetailVo = baseMapper.getSignDetail(sugarSearchDTO);
//		List<SignDetailResultVo> signDetailResult = baseMapper.getSignDetailResult(sugarSearchDTO);
//		List<Long> userIds = signDetailResult.stream().map(SignDetailResultVo::getUserId).distinct().collect(Collectors.toList());
//		Map<Long, List<SignDetailResultVo>> listMap = signDetailResult.stream().collect(Collectors.groupingBy(SignDetailResultVo::getUserId));
//		List<SignDetailVo> list = new ArrayList<>(16);
//		for (Long userId : userIds) {
//			List<SignDetailResultVo> signDetailResultVos = listMap.get(userId);
//			if (signDetailResultVos != null && signDetailResultVos.size() > 0) {
//				SignDetailVo signDetailVo2 = new SignDetailVo();
//				int normalCounts = signDetailResultVos.stream().filter(o ->
//					o.getSignBeLate() == SignStatusEnum.NORMAL.getId() && o.getSignOutLeaveEarly() == SignStatusEnum.NORMAL.getId()
//						&& (o.getSignType() == null || o.getSignType() == 1 || o.getSignOutType() == null || o.getSignOutType() == 1)
//				).collect(Collectors.toList()).size();
//
//
//				int abnormalCounts = signDetailResultVos.stream().filter(o ->
//					o.getSignBeLate() != SignStatusEnum.NORMAL.getId() || o.getSignOutLeaveEarly() != SignStatusEnum.NORMAL.getId()
//						|| Convert.toInt(o.getSignType(), -1) == 2 || Convert.toInt(o.getSignOutType(), -1) == 2
//				).collect(Collectors.toList()).size();
//
//
//				int absenteeismCounts = signDetailResultVos.stream().filter(o ->
//					o.getSignBeLate() == SignStatusEnum.ABSENTEEISM.getId() || o.getSignOutLeaveEarly() == SignStatusEnum.ABSENTEEISM.getId()
//				).collect(Collectors.toList()).size();
//
//				signDetailVo2.setNormalCounts(normalCounts);
//				signDetailVo2.setAbsenteeismCounts(absenteeismCounts);
//				signDetailVo2.setAbnormalCounts(abnormalCounts);
//				signDetailVo2.setUserName(signDetailResultVos.get(0).getUserName());
//				signDetailVo2.setGroupName(signDetailResultVos.get(0).getGroupName());
//				list.add(signDetailVo2);
//			}
//		}
//		signDetailVo.setList(list);
//		return signDetailVo;
//	}
//
	@Override
	public BuildingMaintainDetailVo getBuildingMaintainDetail(SugarSearchDTO sugarSearchDTO) {
		BuildingMaintainDetailVo buildingMaintainDetailVo = new BuildingMaintainDetailVo();
		PlanContentExcelSearchDTO planContentExcelSearchDTO = new PlanContentExcelSearchDTO();
		List<Long> buildIds = new ArrayList<>(2);
		buildIds.add(sugarSearchDTO.getBuildingId());
		planContentExcelSearchDTO.setStartDate(DateUtil.beginOfMonth(new Date()));
		planContentExcelSearchDTO.setEndDate(new Date());
		planContentExcelSearchDTO.setBuildingIds(buildIds);
		planContentExcelSearchDTO.setEndTime(DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd"));
		planContentExcelSearchDTO.setStartTime(DateUtil.format(DateUtil.offsetDay(new Date(), -180), "yyyy-MM-dd"));

		List<Dept> deptList = deptService.selectDeptAndAllChildDepts(sugarSearchDTO.getDeptIds());
		List<Long> deptIds = deptList.stream().map(Dept::getId).collect(Collectors.toList());
		List<ElevatorPrincipalDept> elevatorDepts = elevatorPrincipalDeptService.list(Wrappers.<ElevatorPrincipalDept>lambdaQuery().in(ElevatorPrincipalDept::getDeptId,deptIds));
		List<Long> elevatorIds = elevatorDepts.stream().map(ElevatorPrincipalDept::getElevatorId).collect(Collectors.toList());
		List<MaintainPlanContent> planContents = new ArrayList<>();
		int size = 0;
		if(Func.isNotEmpty(elevatorIds)){
			planContentExcelSearchDTO.setElevatorIds(elevatorIds);
			planContents = baseMapper.getPlanListByBuildingIds(planContentExcelSearchDTO);

			size = elevatorService.getListByBuildingId(sugarSearchDTO.getBuildingId(),elevatorIds).size();
		}

		List<MaintainPlanContent> finishList = planContents.stream().filter(o -> o.getStatus() == MaintainPlanContentStatusEnum.FINISH.getId()).collect(Collectors.toList());
		buildingMaintainDetailVo.setElevatorCounts(size);
		if (planContents.size() == 0) {
			planContentExcelSearchDTO.setStartTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
			planContentExcelSearchDTO.setEndTime(DateUtil.format(DateUtil.offsetDay(new Date(), 180), "yyyy-MM-dd"));
			List<MaintainPlanContent> planContents2 = new ArrayList<>();
			if(Func.isNotEmpty(elevatorIds)){
				planContentExcelSearchDTO.setElevatorIds(elevatorIds);
				planContents2 = baseMapper.getPlanListByBuildingIds(planContentExcelSearchDTO);
			}
			if (planContents2.size() > 0) {
				final List<String> userIdList = Arrays.asList(planContents2.get(0).getUserIds().split(","));
				if (userIdList.size() > 0) {
					final List<User> userList = userMapper.selectBatchIds(userIdList);
					List<User> result = new ArrayList<>();
					deptIds.forEach(e -> {
						result.addAll(userList.stream().filter(o -> o.getStatus() != 2 && o.getDeptId().contains(String.valueOf(e))).collect(Collectors.toList()));
					});
					buildingMaintainDetailVo.setList(new ArrayList<>(result.stream().collect(Collectors.toMap(
						User::getId,
						p -> p,
						(existing, replacement) -> existing
					)).values()));
				}
			}
		} else {
			final List<String> userIdList = Arrays.asList(planContents.get(planContents.size() - 1).getUserIds().split(","));
			if (userIdList.size() > 0) {
				final List<User> userList = userMapper.selectBatchIds(userIdList);
				List<User> result = new ArrayList<>();
				deptIds.forEach(e -> {
					result.addAll(userList.stream().filter(o -> o.getStatus() != 2 && o.getDeptId().contains(String.valueOf(e))).collect(Collectors.toList()));
				});
				buildingMaintainDetailVo.setList(new ArrayList<>(result.stream().collect(Collectors.toMap(
					User::getId,
					p -> p,
					(existing, replacement) -> existing
				)).values()));
			}
		}
		if (finishList.size() > 0) {
			List<Long> finishIds = finishList.stream().map(MaintainPlanContent::getId).collect(Collectors.toList());
			buildingMaintainDetailVo.setFinishRatio(Convert.toBigDecimal(finishList.size()).divide(Convert.toBigDecimal(planContents.size()), 2, BigDecimal.ROUND_HALF_UP));
			List<MaintainPlanContent> workloadList2 = new ArrayList<>();
			for (int i = 0; i < finishList.size(); i++) {
				MaintainPlanContent o = finishList.get(i);
				String updateTime = DateUtil.format(o.getUpdateTime(), "yyyy-MM-dd");
				String signDate = DateUtil.format(o.getPlanDate(), "yyyy-MM-dd");
				if (updateTime.equals(signDate)) {
					workloadList2.add(o);
				}

			}
			buildingMaintainDetailVo.setTimelinessRatio(Convert.toBigDecimal(workloadList2.size()).divide(Convert.toBigDecimal(finishList.size()), 2, BigDecimal.ROUND_HALF_UP));
		}
		return buildingMaintainDetailVo;
	}

	@Override
	public Map<String, Object> getElevatorAndUserInfoPro(SugarSearchDTO sugarSearchDTO) {

		List<Long> deptIds = deptService.selectDeptAndAllChildIds(sugarSearchDTO.getDeptIds());
		Map<String, Object> resultMap = new HashMap<>(2);
		resultMap.put("value", "0.0%");
		resultMap.put("type", "1");
		ElevatorAndUserInfoVo elevatorAndUserInfoVo = new ElevatorAndUserInfoVo();
		Long groupRoleId2 = roleService.getRoleIdByAliases(AuthUtil.getTenantId(), BaseRoleConstant.MAINTENANCE);
		final List<User> userCounts2 = userMapper.selectList(Wrappers.<User>lambdaQuery().like(User::getRoleId,groupRoleId2));
		final List<Long> list2 = new ArrayList<>();
		if(Func.isNotEmpty(userCounts2)){
			deptIds.forEach(e -> {
				list2.addAll(userCounts2.stream().filter(u -> u.getDeptId().contains(String.valueOf(e))).map(User::getId).collect(Collectors.toList()));
			});
		}
		elevatorAndUserInfoVo.setUserCounts(list2.size());

		List<ElevatorPrincipalDept> elevatorDepts = elevatorPrincipalDeptService.list(Wrappers.<ElevatorPrincipalDept>lambdaQuery().in(ElevatorPrincipalDept::getDeptId,deptIds));
		List<Long> elevatorIds = elevatorDepts.stream().map(ElevatorPrincipalDept::getElevatorId).collect(Collectors.toList());
		sugarSearchDTO.setElevatorIds(elevatorIds);
		elevatorAndUserInfoVo.setElevatorCounts(buildingContractPlusService.getValidElevator(sugarSearchDTO));

		// 当前人梯比
		BigDecimal divide = BigDecimal.ZERO;
		if(elevatorAndUserInfoVo.getUserCounts() != null && elevatorAndUserInfoVo.getUserCounts() > 0){
			divide = Convert.toBigDecimal(elevatorAndUserInfoVo.getElevatorCounts()).divide(Convert.toBigDecimal(elevatorAndUserInfoVo.getUserCounts()), 1, RoundingMode.HALF_UP);
		}
		MaintainDayCount dayCount = maintainDayCountService.getOne(Wrappers.<MaintainDayCount>lambdaQuery().eq(MaintainDayCount::getRecordDate, sugarSearchDTO.getTime()).eq(MaintainDayCount::getTenantId, AuthUtil.getTenantId()), false);
		BigDecimal old = BigDecimal.ZERO;
		if (dayCount != null && dayCount.getMaintainUserCount() > 0) {
			old = BigDecimal.valueOf(dayCount.getElevatorCount()).divide(BigDecimal.valueOf(dayCount.getMaintainUserCount()), 1, RoundingMode.HALF_UP);
		}
		if (divide.compareTo(old) != 0 && old.compareTo(BigDecimal.ZERO) != 0) {
			if (divide.compareTo(old) > 0) {
				resultMap.put("type", "2");
			} else {
				resultMap.put("type", "3");
			}
			BigDecimal value = divide.subtract(old).multiply(BigDecimal.valueOf(100)).divide(old, 1, RoundingMode.HALF_UP);
			if (value.compareTo(BigDecimal.ZERO) < 0) {
				value = value.abs();
			}
			resultMap.put("value", value + "%");
		}
		return resultMap;
	}

}
